#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct ListNode
{
  int val;
  struct ListNode *next;
};

// 反转链表的函数
struct ListNode *reverseList(struct ListNode *head)
{
  struct ListNode *prev = NULL;
  struct ListNode *current = head;
  struct ListNode *next = NULL;

  while (current != NULL)
  {
    next = current->next;
    current->next = prev;
    prev = current;
    current = next;
  }

  return prev;
}

// 创建链表（辅助函数）
struct ListNode *createList(int arr[], int n)
{
  struct ListNode *head = NULL;
  struct ListNode *tail = NULL;
  for (int i = 0; i < n; i++)
  {
    struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
    node->val = arr[i];
    node->next = NULL;
    if (head == NULL)
    {
      head = node;
      tail = node;
    }
    else
    {
      tail->next = node;
      tail = node;
    }
  }
  return head;
}

// 打印链表（辅助函数）
void printList(struct ListNode *head)
{
  struct ListNode *p = head;
  while (p != NULL)
  {
    printf("%d ", p->val);
    p = p->next;
  }
  printf("\n");
}

int main()
{
  // 示例：创建链表 1->2->3->4->5
  int arr[] = {1, 2, 3, 4, 5};
  struct ListNode *head = createList(arr, 5);
  printf("原链表: ");
  printList(head);

  // 反转链表
  struct ListNode *reversedHead = reverseList(head);
  printf("反转后: ");
  printList(reversedHead);

  return 0;
}